<!--
 * @Author: [you name]
 * @Date: 2021-10-25 10:02:31
 * @LastEditors: [you name]
 * @LastEditTime: 2021-11-07 23:51:28
 * @Description: 
-->
<template>
  <div class="production">
    <!-- 按钮区域 -->
    <div class="btns">
      <!-- 产品查询 -->
      <el-form
        :inline="true"
        :model="queryParams"
        class="demo-form-inline"
        size="small"
      >
        <!-- 新增添加按钮 -->
        <el-form-item style="margin-right: 10px">
          <el-button @click="toAddHandler" type="primary">添加</el-button>
        </el-form-item>

        <el-form-item>
          <el-input
            v-model="queryParams.name"
            clearable
            placeholder="请输入产品名称关键字"
          ></el-input>
        </el-form-item>
        <el-form-item>
          <el-select
            v-model="queryParams.status"
            clearable
            placeholder="请选择产品状态"
          >
            <el-option label="正常" value="正常"></el-option>
            <el-option label="下架" value="下架"></el-option>
          </el-select>
        </el-form-item>
        <el-form-item>
          <el-select
            v-model="queryParams.productCategoryId"
            clearable
            placeholder="请选择所属栏目"
          >
            <el-option
              v-for="(item, index) in proCategories"
              :key="index"
              :label="item.name"
              :value="item.id"
            ></el-option>
          </el-select>
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="pageQueryProductions"
            >查询</el-button
          >
        </el-form-item>
      </el-form>
    </div>
    <!-- 表格区域 -->
    <el-table :data="tabelData.list" size="small">
      <el-table-column type="index" label="序号"></el-table-column>
      <el-table-column prop="name" label="产品名称"></el-table-column>
      <el-table-column label="图片">
        <template v-slot="scope">
          <el-popover
            placement="right"
            width="200"
            trigger="hover"
            content="这是一段内容,这是一段内容,这是一段内容,这是一段内容。"
          >
            <img :src="scope.row.photo" width="200px" />
            <img slot="reference" :src="scope.row.photo" alt="" width="50px" />
          </el-popover>
        </template>
      </el-table-column>
      <el-table-column prop="price" label="价格"></el-table-column>
      <el-table-column label="状态">
        <template v-slot="scope">
          <el-tag v-if="scope.row.status == '正常'" type="success" size="mini"
            >{{ scope.row.status }}
          </el-tag>
          <el-tag v-else type="danger" size="mini"
            >{{ scope.row.status }}
          </el-tag>
        </template>
      </el-table-column>
      <el-table-column prop="category.name" label="所属栏目"></el-table-column>

      <el-table-column label="操作" align="center">
        <template v-slot="scope">
          <el-button type="text" @click="toEditHandler(scope.row)"
            >编辑</el-button
          >
          <el-button
            v-if="scope.row.status == '正常'"
            type="text"
            style="color: red"
            @click="upDownProductHandler(scope.row.id, $event)"
            >下架</el-button
          >
          <el-button
            v-else
            type="text"
            @click="upDownProductHandler(scope.row.id, $event)"
            >上架</el-button
          >
        </template>
      </el-table-column>
    </el-table>

    <!-- 分页插件区域 -->
    <el-pagination
      background
      @size-change="handleSizeChange"
      @current-change="handleCurrentChange"
      :current-page="tabelData.page"
      :page-sizes="[5, 10, 15, 20]"
      :page-size="tabelData.size"
      layout="total, sizes, prev, pager, next"
      :total="tabelData.total"
    >
    </el-pagination>

    <!-- 模态框 -->
    <el-dialog title="新增商品" :visible.sync="visible">
      <el-form :model="product" ref="proForm" :rules="rules">
        <el-form-item
          label="产品名称"
          :label-width="formLabelWidth"
          prop="name"
        >
          <el-input
            v-model="product.name"
            placeholder="请输入产品名称"
          ></el-input>
        </el-form-item>
        <el-form-item
          label="所属栏目"
          prop="productCategoryId"
          :label-width="formLabelWidth"
        >
          <el-select
            v-model="product.productCategoryId"
            placeholder="请选择所属栏目"
            clearable
          >
            <el-option
              v-for="(item, index) in proCategories"
              :key="index"
              :label="item.name"
              :value="item.id"
            ></el-option>
          </el-select>
        </el-form-item>
        <el-form-item
          label="产品价格"
          prop="price"
          :label-width="formLabelWidth"
        >
          <el-input
            v-model="product.price"
            placeholder="请输入产品价格"
          ></el-input>
        </el-form-item>
        <el-form-item label="产品封面" :label-width="formLabelWidth">
          <el-upload
            class="avatar-uploader"
            action="http://81.69.24.232/pet/jz_upload.php"
            :on-success="handleUploadSuccess"
          >
            <img v-if="imageUrl" :src="imageUrl" class="avatar" />
            <i v-else class="el-icon-plus avatar-uploader-icon"></i>
          </el-upload>
        </el-form-item>
        <el-form-item
          label="产品描述"
          prop="description"
          :label-width="formLabelWidth"
        >
          <el-input
            type="textarea"
            v-model="product.description"
            placeholder="请输入产品描述信息"
          ></el-input>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="visible = false">取 消</el-button>
        <el-button type="primary" @click="toSaveHandler">确 定</el-button>
      </div>
    </el-dialog>
  </div>
</template>
<script>
import request from "@/utils/request";
import { mapState, mapActions } from "vuex";
import qs from "qs";
import _ from "lodash";
export default {
  data() {
    return {
      tabelData: {},
      queryParams: {
        page: 1,
        pageSize: 10,
      },
      visible: false,
      formLabelWidth: "80px",
      product: {},
      imageUrl: "",
      title: "",
      rules: {
        name: [{ required: true, message: "请输入产品名称", trigger: "blur" }],
        productCategoryId: [
          { required: true, message: "请选择所属栏目", trigger: "change" },
        ],
        price: [{ required: true, message: "请输入产品价格", trigger: "blur" }],
        description: [
          { required: true, message: "请输入产品描述信息", trigger: "blur" },
        ],
      },
    };
  },
  //   静态属性
  computed: {
    ...mapState("proCategory", ["proCategories"]),
  },
  methods: {
    ...mapActions("proCategory", ["findAllProductCategories"]),
    // 1.分页查询产品信息
    pageQueryProductions() {
      // 过滤查询参数，将空字符串的键值对删除掉
      for (let key in this.queryParams) {
        if (this.queryParams[key] == "") {
          delete this.queryParams[key];
        }
      }
      // console.log(this.queryParams);
      request
        .get("/product/pageQuery", {
          params: this.queryParams,
        })
        .then((res) => {
          this.tabelData = res.data;
        });
    },
    // 分页size-change事件
    handleSizeChange(pageSize) {
      // 点击分页容量，将最新的pageSize设置到数据模型中
      this.queryParams.pageSize = pageSize;
      //   重新调用分页查询的方法，做数据重载
      this.pageQueryProductions();
    },
    // 分页current-change事件
    handleCurrentChange(page) {
      this.queryParams.page = page;
      this.pageQueryProductions();
    },
    // 商品的上下架功能
    upDownProductHandler(id, e) {
      if (e.target.innerText == "上架") {
        this.$confirm("此操作将上架该文件, 是否继续?", "提示", {
          confirmButtonText: "确定",
          cancelButtonText: "取消",
          type: "warning",
        }).then(() => {
          request
            .get("/product/online", {
              params: { id },
            })
            .then((res) => {
              // 重载数据
              this.pageQueryProductions();
              // 提示成功操作的信息
              this.$message({
                message: res.message,
                type: "success",
              });
            });
        });
      } else {
        this.$confirm("此操作将下架该文件, 是否继续?", "提示", {
          confirmButtonText: "确定",
          cancelButtonText: "取消",
          type: "warning",
        }).then(() => {
          request
            .get("/product/offline", {
              params: { id },
            })
            .then((res) => {
              // 重载数据
              this.pageQueryProductions();
              // 提示成功操作的信息
              this.$message({
                message: res.message,
                type: "success",
              });
            });
        });
      }
    },
    // 添加按钮点击事件
    toAddHandler() {
      this.product = {}; //模态框打开之前，置空表单
      this.title = "新增产品"; //设置模态框的标题
      this.visible = true; //打开模态框
    },
    // 上传插件成功的回调
    handleUploadSuccess(res, file) {
      // 将文件服务器响应的图片在线地址，设置到product
      this.product.photo = res;
      // 将成功上传的图片设置到预览标签上去
      this.imageUrl = res;
    },
    // 表单提交的确认按钮点击事件
    toSaveHandler() {
      // 表单验证
      this.$refs["proForm"].validate((valid) => {
        if (valid) {
          const data = qs.stringify(this.product);
          request.post("/product/saveOrUpdate", data).then((res) => {
            // 数据重载
            this.pageQueryProductions();
            //关闭模态框
            this.visible = false;
            // 提示成功操作的信息
            this.$message.success(res.message);
          });
        }else{
            return false;
        }
      });
    },
    // 编辑按钮
    toEditHandler(row) {
      this.product = _.clone(row); //将当前行数据显示深拷贝后，显示到表单里面去
      this.imageUrl = row.photo;
      this.visible = true; //打开模态框
    },
  },
  created() {
    this.pageQueryProductions(); //   调用分页查询产品信息
    this.findAllProductCategories(); //调用查询所有栏目信息
  },
};
</script>

<style>
.avatar-uploader .el-upload {
  border: 1px dashed #d9d9d9;
  border-radius: 6px;
  cursor: pointer;
  position: relative;
  overflow: hidden;
}
.avatar-uploader .el-upload:hover {
  border-color: #409eff;
}
.avatar-uploader-icon {
  font-size: 28px;
  color: #8c939d;
  width: 178px;
  height: 178px;
  line-height: 178px;
  text-align: center;
}
.avatar {
  width: 178px;
  height: 178px;
  display: block;
}
</style>